package com.gmono.managers;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;

/**
 * 用户管理器
 */
public class UserManager {
    static public Connection c=Common.c;

    static public User getUser(String username)
    {
        User user=new User();
        user.setUsername(username);
        return user.getInfo();
    }
    static public boolean Check(String username,String password)
    {
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        return user.isValid();
    }
    static public Collection<User> getUsers()
    {
        try {
            PreparedStatement s=c.prepareStatement("select * from users ORDER BY id");
            ResultSet set=s.executeQuery();
            ArrayList<User> lst=Common.ResultToCollection(set,User::getObject);
            return lst;
        } catch (SQLException e) {
            return null;
        }

    }
    static public boolean addUser(User u)
    {
        if(u.isExists()) return false;
        try {
            PreparedStatement s=c.prepareStatement("insert into users(username, name, phonenumber, password) VALUES (?,?,?,?)");
            s.setString(1,u.getUsername());
            s.setString(2,u.getName());
            s.setString(3,u.getPhonenumber());
            s.setString(4,u.getPassword());
            s.executeUpdate();
            return true;
        } catch (SQLException e) {
            return false;
        }
    }

    static public boolean deleteUser(String username)
    {
        try {
            PreparedStatement s=c.prepareStatement("delete from users WHERE username=?");
            s.setString(1,username);
            s.executeUpdate();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

    }

}
